import { createRouter, createWebHistory } from 'vue-router'
import getUser from '@/api/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../views/HomeView.vue')
    },
    {
      path: '/item',
      name: 'item',
      component: () => import('../views/ItemView.vue')
    },
    {
      path: '/items/category',
      name: 'category',
      component: () => import('../views/CategoryView.vue')
    },
    {
      path: '/detail/:id',
      name: 'detail',
      component: () => import('../views/GoodsDetailsView.vue')
    },
    {
      path: '/brand/:id',
      name: 'brand',
      component: () => import('../views/BrandDetailsView.vue')
    },
    {
      path: '/cart',
      name: 'cart',
      component: () => import('../views/CartView.vue')
    },
    {
      path: '/my',
      name: 'my',
      component: () => import('../views/MineView.vue')
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    }
  ]
})

// 添加全局前置守卫
router.beforeEach(async (to, from, next) => {
  if (to.path === '/my') {
    try {
      const res = await getUser()
      if (res.errno === 0 && res.errmsg === '成功') {
        next() // 验证通过，允许进入
      } else {
        next('/login')
      }
    } catch (error) {
      console.error('获取用户信息失败', error)
      next('/login')
    }
  } else if (to.path === '/cart') {
    try {
      const res = await getUser()
      if (res.errno === 0 && res.errmsg === '成功') {
        next() // 验证通过，允许进入
      } else {
        next('/login')
      }
    } catch (error) {
      console.error('获取用户信息失败', error)
      next('/login')
    }
  } else {
    next()
  }
})

// const verify = async () => {
//   const res = await getUser()
//   if (res.errno === 0 && res.errmsg === '成功') {
//     return true
//   } else {
//     return false
//   }
// }

export default router
